package itbour.onetouchshow.activity.challengezone.filter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.video.cut.widget.EditRangeSeekBarView;
import com.video.cut.widget.TrimmerView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.App;
import itbour.onetouchshow.AppCache;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.FreeCreateOrigin;
import itbour.onetouchshow.bean.LetterBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.AssetsDataUtils;
import itbour.onetouchshow.utils.DisplayUtil;
import itbour.onetouchshow.utils.FileUtils;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.aliyun.AliRequestUtils;
import itbour.onetouchshow.widget.FontAttributeSettingLayout;
import itbour.onetouchshow.widget.FontWithOperationLayout;

/**
 * Created by Administrator on 2018/7/5.
 */

public class VideoEditTimmerCutActivity extends MVPBaseActivity implements FontAttributeSettingLayout.onAttributeItemClickListener {

    static final int VIDEO_PLAY = 6;
    /**
     * 是否处于编辑状态
     */
    protected boolean isEditState;
    /**
     * 视频宽高以及URL
     */
    @BindView(R.id.trimmer_view)
    TrimmerView trimmerView;
    @BindView(R.id.video_loader)
    VideoView mVideoView;
    @BindView(R.id.rl_play)
    RelativeLayout rlPlay;
    @BindView(R.id.id_ig_play)
    ImageView idIgPlay;
    @BindView(R.id.layout_surface_view)
    RelativeLayout mLinearVideo;
    @BindView(R.id.video_loading)
    ProgressBar videoLoading;
    @BindView(R.id.rl_letter_layout)
    RelativeLayout letterLayout;
    EpVideo epVideo;
    @BindView(R.id.font_setting)
    FontAttributeSettingLayout fontSetting;
    @BindView(R.id.ll_base_root)
    LinearLayout llBaseRoot;
    @BindView(R.id.tv_add_letter)
    TextView tvAddLetter;
    @BindView(R.id.ll_add_letter)
    LinearLayout llAddLetter;
    private OneToucDialog oneToucDialog;
    private String localVideoUrl;
    private String videoPath;
    private Handler mAnimationHandler = new Handler();
    private Runnable mAnimationRunnable = new Runnable() {

        @Override
        public void run() {
            updateVideoProgress();
        }
    };
    //键盘真实高度
    private int realKeyboardHeight;
    //底部弹出的输入框Window
    private PopupWindow editContentPopWindow;
    //当前被选中的字幕输入框
    private FontWithOperationLayout currentLetterLayout = null;
    //所有字幕集合
    private List<FontWithOperationLayout> allLetterList = new ArrayList<>();
    //视频的宽高缩放指数
    private float videoScale;
    //视频真实高度
    private int videoHeight;
    //视频真实宽度
    private int videoWidth;
    //字体存放的路径
    private String fontSavePath = AppCache.getInstance().VIDEO_SAVE_DIR + File.separator + "Fonts";
    //初始宽度多加的值 dp
    private int addWidthDp = 15;
    //字幕默认延续时间
    private int letterDuration = 3000;
    private List<LetterBean> letterBeans = new ArrayList<>();

    private Handler timeHandler;
    private Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            resetAllLetterViewStatus(mVideoView.getCurrentPosition());
            timeHandler.postDelayed(this, 300);
        }
    };

    private FreeCreateOrigin.MainAssetsBean mainAssetsBean;
    private String addLetterFilePath;
    private OSSAsyncTask<PutObjectResult> putObjectResultOSSAsyncTask;

    public static Intent getLaunchIntent(Context context, String videoUrl, String userType) {
        Intent intent = new Intent(context, VideoEditTimmerCutActivity.class);
        intent.putExtra(AppConst.KEY_VIDEO_URL, videoUrl);
        intent.putExtra(AppConst.KEY_USER_TYPE, userType);
        return intent;
    }

    public static Intent getLaunchIntent(Context context, FreeCreateOrigin.MainAssetsBean mainAssetsBean) {
        Intent intent = new Intent(context, VideoEditTimmerCutActivity.class);
        intent.putExtra(AppConst.KEY_VIDEO_MAINASSETSBEAN, mainAssetsBean);
        return intent;
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        timeHandler = new Handler();
        timeHandler.postDelayed(timeRunnable, 300);
        copyFontToLocalDir(getViewContext(), "Fonts", fontSavePath);
        Bundle extras = getIntent().getExtras();
        String videoUrl = null;
        if (extras != null) {
            videoUrl = extras.getString(AppConst.KEY_VIDEO_URL);
            mainAssetsBean = (FreeCreateOrigin.MainAssetsBean)
                    getIntent().getSerializableExtra(AppConst.KEY_VIDEO_MAINASSETSBEAN);
        }
        if (mainAssetsBean != null) {
            videoUrl = mainAssetsBean.getUrl();
        }

        if (videoUrl.startsWith("http") || videoUrl.startsWith("https")) {
            String localVideoUrl = SpUtils.getInstance().getString(videoUrl);
            if (TextUtils.isEmpty(localVideoUrl)) {
                AssetsDataUtils.doDonwloadVideo(videoUrl, new AssetsDataUtils.DownLoadVideoListener() {
                    @Override
                    public void onSuccess(String path) {
                        videoPath = path;
                        mHandler.sendEmptyMessage(VIDEO_PLAY);
                    }

                    @Override
                    public void onFail() {

                    }
                });
            } else {
                trimmerView.initVideoByURI(localVideoUrl);
                initVideoByURI(localVideoUrl);
                epVideo = new EpVideo(localVideoUrl);
            }
        } else {
            localVideoUrl = videoUrl;
            trimmerView.initVideoByURI(localVideoUrl);
            initVideoByURI(localVideoUrl);
            epVideo = new EpVideo(localVideoUrl);
        }


        fontSetting.setOnAttributeItemClickListener(this);
        trimmerView.setOnScrollToVideoProgress(new TrimmerView.OnScrollToVideoProgress() {
            @Override
            public void progress(long progress) {
                if (trimmerView.getVideoState().equals(TrimmerView.VideoState.PAUSE)) {
                    mVideoView.seekTo((int) progress);
                    videoPause();
                }
            }
        });

        trimmerView.setOnUpdateSeekBarProgress(new EditRangeSeekBarView.OnUpdateSeekBarProgress() {
            @Override
            public void onRangeSeekBarValuesChanged(float minValue, float maxValue, long startTime, long endTime) {
                if (currentLetterLayout == null) return;
                currentLetterLayout.setLetterStartTime(startTime);
                currentLetterLayout.setLetterEndTime(endTime);
            }
        });

        idIgPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVideoView.isPlaying()) {
                    videoPause();
                } else {
                    videoPlay();
                }
            }
        });
    }

    private void updateVideoProgress() {
        if (mVideoView == null) return;
        if (trimmerView == null) return;
        long currentPosition = mVideoView.getCurrentPosition();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int v = (int) (currentPosition / trimmerView.getAverageMsPx());
                trimmerView.getmVideoThumbRecyclerView().scrollTo(v);
            }
        });
        if (trimmerView.getVideoState().equals(TrimmerView.VideoState.PAUSE)) {
            videoPause();
        } else {
            mAnimationHandler.postDelayed(mAnimationRunnable, 0);
        }
    }

    public void dismissDialog() {
        UIUtils.getHandler().post(new Runnable() {
            @Override
            public void run() {
                try {
                    if ((oneToucDialog != null) && oneToucDialog.isShowing()) {
                        oneToucDialog.dismiss();
                    }
                    dismissProgressDialog();
                } catch (final IllegalArgumentException e) {
                    // Handle or log or ignore
                } catch (final Exception e) {
                    // Handle or log or ignore
                } finally {
                    oneToucDialog = null;
                }
            }
        });

    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_edit_timmer_cut;
    }

    //private int currentPosition;
    @Override
    public void onPause() {
        super.onPause();
        timeHandler.removeCallbacks(timeRunnable);
        //currentPosition = mVideoView.getCurrentPosition();
        mVideoView.stopPlayback();
    }

    @Override
    protected void onResume() {
        super.onResume();
        timeHandler.postDelayed(timeRunnable, 300);
        // mVideoView.seekTo(currentPosition);
        mVideoView.resume();
    }

    protected void initView() {
        super.initView();
        setTitleText("视频编辑");
        getToolBarView().getRightTextView().setVisibility(View.VISIBLE);
        getToolBarView().getRightTextView().setText("保存");
        getToolBarView().getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (allLetterList == null || allLetterList.size() <= 0) {
                    //未添加字幕
                } else {

                    showProgressDialogWithText("视频合成中");
                    //添加了字幕
                    List<LetterBean> letterBeanList = new ArrayList<>();
                    for (int i = 0; i < allLetterList.size(); i++) {
                        FontWithOperationLayout font = allLetterList.get(i);

                        LetterBean letterBean = new LetterBean();
                        try {
                            letterBean.setTe(URLEncoder.encode(font.getText(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        letterBean.setFs(font.getFontTextSize() * font.getVideoScale());
                        letterBean.setStartTime((int) (font.getLetterStartTime() / 1000));
                        letterBean.setDuration((font.getLetterEndTime() - font.getLetterStartTime()) / 1000);
                        letterBean.setFn(font.getFont().getName());
                        LetterBean.ColorBean colorBean = new LetterBean.ColorBean();
                        colorBean.setR(font.getR());
                        colorBean.setB(font.getB());
                        colorBean.setG(font.getG());
                        letterBean.setColor(colorBean);
                        LetterBean.PosBean posBean = new LetterBean.PosBean();
                        posBean.setX(font.getRealLeftMargin());
                        posBean.setY(font.getRealTopMargin());
                        posBean.setH(font.getLetterRealHeight());
                        posBean.setW(font.getLetterRealWidth());
                        letterBean.setPos(posBean);

                        letterBeanList.add(letterBean);
                        mainAssetsBean.setSubTitles(letterBeanList);
                        String path = saveBitmapToLocal(getCacheBitmapFromView(font.getFontTextView(), font.isHasAddWidth()));
                        epVideo.addDraw(new EpDraw(path, font.getRealLeftMargin(), font.getRealTopMargin(), font.getLetterRealWidth(), font.getLetterRealHeight(), false, (int) (font.getLetterStartTime() / 1000), (int) (font.getLetterEndTime() / 1000)));
                    }
                    String outPutFile = FileUtils.getDownloadDir() + File.separator + "clipOut" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
                    EpEditor.exec(epVideo, new EpEditor.OutputOption(outPutFile), new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            addLetterFilePath = outPutFile;
                            cliptAndSave();
                        }

                        @Override
                        public void onFailure() {

                        }

                        @Override
                        public void onProgress(float progress) {

                        }
                    });
                }


            }
        });
    }

    @Override
    public void onBackPressed() {
        if (trimmerView != null) {
            trimmerView.onCancelClicked();
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (trimmerView != null) {
            trimmerView.onDestroy();
        }
        timeHandler.removeCallbacks(timeRunnable);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void setUpListeners() {
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoPrepared(mp);
                mp.setLooping(true);
            }
        });
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                ///videoPlay();
                //mp.setLooping(true);
            }
        });
    }

    public void initVideoByURI(final String videoURI) {
        try {
            setUpListeners();
            mVideoView.setVideoPath(videoURI);
            mVideoView.requestFocus();

            UIUtils.getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    videoPlay();
                }
            }, 500);

        } catch (Exception e) {
        }
    }

    private void videoPlay() {
        setEditState(false);
        idIgPlay.setImageResource(com.gup.video.R.drawable.ic_player_pause);
        mAnimationHandler.post(mAnimationRunnable);
        trimmerView.setVideoState(TrimmerView.VideoState.PLAY);
        trimmerView.scrollForCurrentPosition(mVideoView.getCurrentPosition());
        mVideoView.start();
    }

    public void videoPause() {
        idIgPlay.setImageResource(R.drawable.ic_player_start);
        mVideoView.pause();
        trimmerView.setVideoState(TrimmerView.VideoState.PAUSE);
        mAnimationHandler.removeCallbacks(mAnimationRunnable);
    }

//    @Override
//    public void finish() {
//        if (trimmerView != null) {
//            trimmerView.onCancelClicked();
//            trimmerView.setOnTrimVideoListener(null);
//            trimmerView.onDestroy();
//        }
//        super.finish();
//    }

    private void videoPrepared(MediaPlayer mp) {
        ViewGroup.LayoutParams lp = mVideoView.getLayoutParams();
        videoWidth = mp.getVideoWidth();
        videoHeight = mp.getVideoHeight();
        float videoProportion = (float) videoWidth / (float) videoHeight;
        int screenWidth = mLinearVideo.getWidth();
        int screenHeight = mLinearVideo.getHeight();
        float screenProportion = (float) screenWidth / (float) screenHeight;

        if (videoProportion > screenProportion) {
            lp.width = screenWidth;
            lp.height = (int) ((float) screenWidth / videoProportion);
        } else {
            lp.width = (int) (videoProportion * (float) screenHeight);
            lp.height = screenHeight;
        }
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) letterLayout.getLayoutParams();
        params.width = lp.width;
        params.height = lp.height;
        videoScale = (float) videoWidth / (float) params.width;
        letterLayout.setLayoutParams(params);
        mVideoView.setLayoutParams(lp);
        rlPlay.setLayoutParams(lp);
    }

    //添加字幕点击
    @OnClick(R.id.tv_add_letter)
    public void onViewClicked() {
        showAddLetter(false);
        addADefaultLetterTextView();
        videoPause();
        LetterBean letterBean = addALetterWithData(mVideoView.getCurrentPosition(), 0);
        trimmerView.setInitLetterBean(letterBean);
        setEditState(true);
    }

    @Override
    public void onEditLetterClick() {
        //底部编辑点击
        if (checkCurrentLayoutIsNull()) return;
        showEditPopWindows();
    }

    @Override
    public void onFontClick(FontAttributeSettingLayout.Font font) {
        //字体点击
        if (checkCurrentLayoutIsNull()) return;
        currentLetterLayout.setFont(font);
        fontSetting.setFont(font);
    }

    @Override
    public void onDeleteLetterClick() {
        //删除点击
        if (checkCurrentLayoutIsNull()) return;
        new OneToucDialog.Builder(this)
                .content("确定删除此字幕吗")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                if (currentLetterLayout != null) {

                    LetterBean letterBean = new LetterBean();
                    letterBean.setId(currentLetterLayout.getId());
                    trimmerView.deleteImageHotView(letterBean);

                    letterLayout.removeView(currentLetterLayout);
                    allLetterList.remove(currentLetterLayout);
                    currentLetterLayout = null;
                }
                showAddLetter(true);
                setEditState(false);
                fontSetting.clearAllAttribute();


            }
        }).negativeText("再想想").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                dialog.dismiss();
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();


    }

    @Override
    public void onSaveLetterClick() {
        //保存点击
        if (currentLetterLayout != null) {
            currentLetterLayout.setLayoutSelect(false);
            currentLetterLayout = null;
            fontSetting.clearAllAttribute();
        }
        showAddLetter(true);
        setEditState(false);


    }

    public void cliptAndSave() {
        String Video = ".mp4";
        String videoName = AliRequestUtils.getInstance().createFileName("video", App.getLoginBean().getUserInfo().getUserId() + "") + Video;
        String IMAGE = ".png";
        String imageName = AliRequestUtils.getInstance().createFileName("image", App.getLoginBean().getUserInfo().getUserId() + "") + IMAGE;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap videoThumbnail = ImageLoader.getInstance().getVideoThumbnail(addLetterFilePath);
                    AliRequestUtils.getInstance().setName(imageName);
                    File imagefile = AliRequestUtils.getInstance().saveBitmapFile(videoThumbnail, FileUtils.getJpgFileName(addLetterFilePath));
                    App.ossClient.putObject(AliRequestUtils.getInstance().putObjectRequest(imagefile.getAbsolutePath()));
                    //App.ossClient.putObject(list.get(0));
                    String imagePathName = AppConfig.UPLOAD_ALYUN + imageName;
                    AliRequestUtils.getInstance().setName(videoName);
                    PutObjectRequest put = new PutObjectRequest(AppConst.OSSBUCKETNAME, videoName, addLetterFilePath);
                    // 异步上传时可以设置进度回调
                    put.setProgressCallback((request, currentSize, totalSize) -> {
                        // int progress = (int) (currentSize * 100 / totalSize);
                    });
                    putObjectResultOSSAsyncTask = App.ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                            dismissDialog();
                            String videoPathfile = AppConfig.UPLOAD_ALYUN + videoName;
                            //存储本地路径和网络路径对应  网络路径对应本地路径
                            SpUtils.getInstance().saveString(videoPathfile, addLetterFilePath);
                            UserMakeTag userMakeTag = UserMakeTag.CUTUPDATE;
                            userMakeTag.setTag(videoPathfile);
                            UIUtils.getHandler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    EventBus.getDefault().post(userMakeTag);
                                    dismissDialog();
                                    finish();
                                }
                            }, 300);
                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                            // 请求异常
                            dismissDialog();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    dismissProgressDialog();
                }
            }
        }).start();
    }


    @Override
    public void onFontColorClick(int r, int g, int b, String type) {
        //颜色回调
        if (currentLetterLayout != null) {
            currentLetterLayout.setFontTextColor(r, g, b);
            fontSetting.setFontColor(r, g, b);
        }
    }

    @Override
    public void onFontSizeChange(int fontSize) {
        //字体大小回调
        if (currentLetterLayout != null) {
            currentLetterLayout.setFontTextSize(fontSize);
            fontSetting.setFontSize(fontSize);
        }
    }

    public void selectLetterTextView() {
        videoPause();
        float letterEndTime = currentLetterLayout.getLetterEndTime();
        float letterStartTime = currentLetterLayout.getLetterStartTime();
        int v = (int) (letterStartTime / trimmerView.getAverageMsPx());
        mVideoView.seekTo((int) letterEndTime);
        trimmerView.getmVideoThumbRecyclerView().scrollTo(v);
        LetterBean letterBean = new LetterBean();
        letterBean.setId(currentLetterLayout.getId());
        letterBean.setStartTime(letterStartTime);
        letterBean.setDuration(letterEndTime - letterStartTime);
        trimmerView.setUpdataBean(letterBean);

    }

    public int getLetterLayoutId() {
        if (allLetterList.size() == 0) {
            return allLetterList.size() + 1;
        } else {
            return (allLetterList.get(allLetterList.size() - 1).getId()) + 1;
        }
    }

    //添加一个默认字幕
    private void addADefaultLetterTextView() {
        if (this.currentLetterLayout != null) this.currentLetterLayout.setSelected(false);
        FontWithOperationLayout fontWithOperationLayout = new FontWithOperationLayout(getViewContext());
        fontWithOperationLayout.setId(getLetterLayoutId());
        if (currentLetterLayout == null) currentLetterLayout = fontWithOperationLayout;
        fontWithOperationLayout.setVisibility(View.INVISIBLE);
        //字幕开始时间
        fontWithOperationLayout.setLetterStartTime(mVideoView.getCurrentPosition());
        //字幕结束时间
        fontWithOperationLayout.setLetterEndTime(mVideoView.getCurrentPosition() + letterDuration > mVideoView.getDuration() ? mVideoView.getDuration() : mVideoView.getCurrentPosition() + letterDuration);

        letterLayout.addView(fontWithOperationLayout);
        allLetterList.add(fontWithOperationLayout);
        fontWithOperationLayout.setLayoutSelect(true);
        fontWithOperationLayout.setOnDoubleClickListener(new FontWithOperationLayout.onDoubleClickListener() {
            @Override
            public void onDoubleClick(View view) {
                selectOneLetter(fontWithOperationLayout);
                showEditPopWindows();
            }

            @Override
            public void onSingleClick(View view) {
                resetLetterSelect();
                if (!fontWithOperationLayout.isSelected()) {
                    fontWithOperationLayout.setLayoutSelect(true);
                    currentLetterLayout = fontWithOperationLayout;
                    showAddLetter(false);
                    //TODO
                    selectLetterTextView();
                    setEditState(true);
                    fontSetting.setFont(fontWithOperationLayout.getFont());
                    fontSetting.setFontSize(fontWithOperationLayout.getFontTextSize());
                    fontSetting.setFontColor(fontWithOperationLayout.getR(), fontWithOperationLayout.getG(), fontWithOperationLayout.getB());
                }
            }
        });
        //获取实际宽高
        fontWithOperationLayout.post(new Runnable() {
            @Override
            public void run() {
                //包含字幕与图标的宽高
                int fontOperationLayoutWidth = 0;
                int fontOperationLayoutHeight = 0;
                //使用设置margin的方式使字幕移动到中间 方便移动时的计算
                fontOperationLayoutWidth = fontWithOperationLayout.getWidth();
                fontOperationLayoutHeight = fontWithOperationLayout.getHeight();

                fontOperationLayoutWidth += DisplayUtil.dip2px(getViewContext(), addWidthDp);

                //设置实际的宽高 设置右下角缩放的图标
                fontWithOperationLayout.setFixedTextViewWidthAndHeight(fontOperationLayoutWidth, fontOperationLayoutHeight);
                fontWithOperationLayout.setFixedLayoutWidthAndHeight(fontOperationLayoutWidth + fontWithOperationLayout.getBitMapWidth() / 2, fontOperationLayoutHeight + fontWithOperationLayout.getBitMapHeight() / 2);
                fontWithOperationLayout.resetImageLocation();
                fontWithOperationLayout.setHasAddWidth(true);

                int containerHeight = letterLayout.getLayoutParams().height;
                int containerWidth = letterLayout.getLayoutParams().width;
                fontWithOperationLayout.setParentHeight(containerHeight);
                fontWithOperationLayout.setParentWidth(containerWidth);
                fontWithOperationLayout.setVideoScale(videoScale);


                //设置居中
                float offSetY = (containerHeight / 2) - fontOperationLayoutHeight / 2;
                float offSetX = (containerWidth / 2) - fontOperationLayoutWidth / 2;
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) fontWithOperationLayout.getLayoutParams();
                params.leftMargin = (int) offSetX;
                params.topMargin = (int) offSetY;
                params.rightMargin = -fontOperationLayoutWidth;
                params.bottomMargin = -fontOperationLayoutHeight;
                fontWithOperationLayout.setLayoutParams(params);
                fontWithOperationLayout.setRealLeftMargin((int) (params.leftMargin * videoScale));
                fontWithOperationLayout.setRealTopMargin((int) (params.topMargin * videoScale));
                fontWithOperationLayout.setVisibility(View.VISIBLE);

                currentLetterLayout = fontWithOperationLayout;
            }
        });

    }

    //选中一个字幕
    private void selectOneLetter(FontWithOperationLayout fontWithOperationLayout) {
        resetLetterSelect();
        if (!fontWithOperationLayout.isSelected()) {
            fontWithOperationLayout.setLayoutSelect(true);
            currentLetterLayout = fontWithOperationLayout;
            showAddLetter(false);
            setEditState(true);
            fontSetting.setFont(fontWithOperationLayout.getFont());
            fontSetting.setFontSize(fontWithOperationLayout.getFontTextSize());
            fontSetting.setFontColor(fontWithOperationLayout.getR(), fontWithOperationLayout.getG(), fontWithOperationLayout.getB());
        }
    }

    //根据数据模型添加一个字幕
    private LetterBean addALetterWithData(float startTime, float endTime) {
        currentLetterLayout.setLetterStartTime(startTime);
        currentLetterLayout.setLetterEndTime(startTime + letterDuration);
        LetterBean letterInfo = new LetterBean();
        letterInfo.setStartTime(startTime);
        letterInfo.setDuration(letterDuration);
        letterInfo.setTe("编辑文本");
        letterInfo.setId(currentLetterLayout.getId());
        return letterInfo;
    }

    public boolean isEditState() {
        return isEditState;
    }

    /**
     * 编辑状态显示Seekbar
     */
    public void setEditState(boolean editState) {
        isEditState = editState;
        trimmerView.setEditState(isEditState);
    }

    public void refrshEditState() {

//        if (trimmerView.getRangeSeekBarView()==null)return;
//       if (isEditState){
//           trimmerView.getRangeSeekBarView().setVisibility(View.VISIBLE);
//       }else {
//           trimmerView.getRangeSeekBarView().setVisibility(View.INVISIBLE);
//       }
    }

    public String getLetterBeanId() {
        return letterBeans.size() + 1 + "";
    }


    //根据数据模型添加一个字幕
    private void addALetterWithData(LetterBean letterInfo) {
        FontWithOperationLayout fontWithOperationLayout = new FontWithOperationLayout(getViewContext());
        fontWithOperationLayout.setVisibility(View.INVISIBLE);

        //设置属性

        //字幕开始时间
        fontWithOperationLayout.setLetterStartTime(letterInfo.getStartTime() * 1000);
        fontWithOperationLayout.setLetterEndTime(letterInfo.getStartTime() * 1000 + letterInfo.getDuration() * 1000);
        try {
            fontWithOperationLayout.setText(URLDecoder.decode(letterInfo.getTe(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        fontWithOperationLayout.setFontTextColor(letterInfo.getColor().getR(), letterInfo.getColor().getG(), letterInfo.getColor().getB());
        fontWithOperationLayout.setFontTextSize(Math.round(letterInfo.getFs() / videoScale));
        //根据返回数据结构判断字体
        fontWithOperationLayout.setFont((letterInfo.getFn().equals(FontAttributeSettingLayout.Font.blackFont.getName()) ? FontAttributeSettingLayout.Font.blackFont : FontAttributeSettingLayout.Font.defaultFont));


        letterLayout.addView(fontWithOperationLayout);
        allLetterList.add(fontWithOperationLayout);
        fontWithOperationLayout.setLayoutSelect(false);
        fontWithOperationLayout.setOnDoubleClickListener(new FontWithOperationLayout.onDoubleClickListener() {
            @Override
            public void onDoubleClick(View view) {
                showEditPopWindows();
            }

            @Override
            public void onSingleClick(View view) {
                resetLetterSelect();
                if (!fontWithOperationLayout.isSelected()) {
                    fontWithOperationLayout.setLayoutSelect(true);
                    currentLetterLayout = fontWithOperationLayout;
                    showAddLetter(false);
                    setEditState(false);
                    fontSetting.setFont(fontWithOperationLayout.getFont());
                    fontSetting.setFontSize(fontWithOperationLayout.getFontTextSize());
                    fontSetting.setFontColor(fontWithOperationLayout.getR(), fontWithOperationLayout.getG(), fontWithOperationLayout.getB());
                }
            }
        });


        //获取实际宽高
        fontWithOperationLayout.post(new Runnable() {
            @Override
            public void run() {
                //包含字幕与图标的宽高
                int fontOperationLayoutWidth = 0;
                int fontOperationLayoutHeight = 0;
                //使用设置margin的方式使字幕移动到中间 方便移动时的计算
                fontOperationLayoutWidth = letterInfo.getPos().getW();
                fontOperationLayoutHeight = letterInfo.getPos().getH();

                //设置实际的宽高 设置右下角缩放的图标
                fontWithOperationLayout.setFixedTextViewWidthAndHeight(fontOperationLayoutWidth, fontOperationLayoutHeight);
                fontWithOperationLayout.setFixedLayoutWidthAndHeight(fontOperationLayoutWidth + fontWithOperationLayout.getBitMapWidth() / 2, fontOperationLayoutHeight + fontWithOperationLayout.getBitMapHeight() / 2);
                fontWithOperationLayout.resetImageLocation();
                fontWithOperationLayout.setHasAddWidth(true);

                int containerHeight = letterLayout.getLayoutParams().height;
                int containerWidth = letterLayout.getLayoutParams().width;
                fontWithOperationLayout.setParentHeight(containerHeight);
                fontWithOperationLayout.setParentWidth(containerWidth);
                fontWithOperationLayout.setVideoScale(videoScale);

                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) fontWithOperationLayout.getLayoutParams();
                params.leftMargin = (int) (letterInfo.getPos().getX() / videoScale);
                params.topMargin = (int) (letterInfo.getPos().getY() / videoScale);
                params.rightMargin = -fontOperationLayoutWidth;
                params.bottomMargin = -fontOperationLayoutHeight;
                fontWithOperationLayout.setLayoutParams(params);
                fontWithOperationLayout.setRealLeftMargin((letterInfo.getPos().getX()));
                fontWithOperationLayout.setRealTopMargin((letterInfo.getPos().getY()));
                fontWithOperationLayout.setVisibility(View.VISIBLE);

            }
        });
    }

    //重置所有字幕的选中状态
    private void resetLetterSelect() {
        if (allLetterList != null && allLetterList.size() > 0) {
            for (FontWithOperationLayout t : allLetterList) {
                t.setLayoutSelect(false);
            }
        }
        fontSetting.clearAllAttribute();
    }

    //判断当前是否有选中的字幕
    private boolean checkCurrentLayoutIsNull() {
        if (currentLetterLayout == null) {
            T_.showCustomToast("请添加或选中一个字幕");
            return true;
        }
        return false;
    }

    //是否显示添加字幕按钮
    private void showAddLetter(boolean show) {
        llAddLetter.setVisibility(show ? View.VISIBLE : View.GONE);
        fontSetting.setVisibility(show ? View.GONE : View.VISIBLE);

        // setEditState(show);
    }

    //计算输入法高度
    private void initSoftInputHeight() {
        llBaseRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            private int statusBarHeight;

            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                // 使用最外层布局填充，进行测算计算
                llBaseRoot.getWindowVisibleDisplayFrame(r);
                int screenHeight = llBaseRoot.getRootView().getHeight();
                int heightDiff = screenHeight - (r.bottom - r.top);
                if (heightDiff > 100) {
                    // 如果超过100个像素，它可能是一个键盘。获取状态栏的高度
                    statusBarHeight = 0;
                }
                try {
                    Class<?> c = Class.forName("com.android.internal.R$dimen");
                    Object obj = c.newInstance();
                    Field field = c.getField("status_bar_height");
                    int x = Integer.parseInt(field.get(obj).toString());
                    statusBarHeight = getViewContext().getResources().getDimensionPixelSize(x);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                realKeyboardHeight = heightDiff - statusBarHeight;
                Log.e("键盘", "keyboard height(单位像素) = " + realKeyboardHeight);
                if (realKeyboardHeight > 0)
                    editContentPopWindow.showAtLocation(llBaseRoot, Gravity.BOTTOM, 0, realKeyboardHeight);
                else {
                    if (editContentPopWindow != null && editContentPopWindow.isShowing()) {
                        editContentPopWindow.dismiss();
                    }
                }
            }
        });

    }

    //弹出输入内容框与输入法
    private void showEditPopWindows() {
        View view = LayoutInflater.from(getViewContext()).inflate(R.layout.view_font_input_dialog, null);
        EditText etContent = view.findViewById(R.id.et_content);
        ImageButton iSave = view.findViewById(R.id.i_btn_save);
        editContentPopWindow = new PopupWindow(view);
        editContentPopWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        editContentPopWindow.setHeight(DisplayUtil.dip2px(getViewContext(), 50));
        editContentPopWindow.setBackgroundDrawable(new ColorDrawable());
        editContentPopWindow.setFocusable(true);
        editContentPopWindow.setOutsideTouchable(true);
        editContentPopWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        iSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editContentPopWindow.dismiss();
            }
        });
        if (currentLetterLayout != null) {
            etContent.setText(currentLetterLayout.getText());
        }
        etContent.setSelection(etContent.getText().length());
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (currentLetterLayout != null) {
                    currentLetterLayout.setText(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        initSoftInputHeight();

        InputMethodManager inputManager =
                (InputMethodManager) llBaseRoot.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    //将字体从assets拷贝到本地文件夹
    private void copyFontToLocalDir(Context context, String oldPath, String newPath) {
        try {
            String fileNames[] = getViewContext().getAssets().list(oldPath);
            if (fileNames.length > 0) {
                File file = new File(newPath);
                file.mkdirs();
                for (String fileName : fileNames) {
                    copyFontToLocalDir(context, oldPath + "/" + fileName, newPath + "/" + fileName);
                }
            } else {
                InputStream is = context.getAssets().open(oldPath);
                File ff = new File(newPath);
                if (!ff.exists()) {
                    FileOutputStream fos = new FileOutputStream(ff);
                    byte[] buffer = new byte[1024];
                    int byteCount = 0;
                    while ((byteCount = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, byteCount);
                    }
                    fos.flush();
                    is.close();
                    fos.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //将View中的内容转换为Bitmap 是否需要减去初始加的优化显示的宽度
    private Bitmap getCacheBitmapFromView(View view, boolean reduce) {
        final boolean drawingCacheEnabled = true;
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        view.buildDrawingCache(drawingCacheEnabled);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        int px = DisplayUtil.dip2px(getViewContext(), 1);
        int addWidthPx = DisplayUtil.dip2px(getViewContext(), addWidthDp);
        //view是带边框的 截取边框的内容保证水印无线条
        return Bitmap.createBitmap(bitmap, px, px, view.getWidth() - px * 2 - (reduce ? addWidthPx : 0), view.getHeight() - px * 2, null, false);
    }

    //将Bitmap保存到本地
    private String saveBitmapToLocal(Bitmap mBitmap) {
        File filePic;
        try {
            filePic = new File(AppCache.getInstance().VIDEO_SAVE_DIR + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".png");
            filePic = new File(AppCache.getInstance().VIDEO_SAVE_DIR + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + Math.random() * 1000 + ".png");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }

    //根据时间重置所有的字幕是否显示隐藏
    private void resetAllLetterViewStatus(float duration) {
        for (FontWithOperationLayout operationLayout : allLetterList) {
            if (duration < operationLayout.getLetterStartTime() - 20 || duration > operationLayout.getLetterEndTime()) {
                operationLayout.setVisibility(View.GONE);
            } else {
                operationLayout.setVisibility(View.VISIBLE);
                //播放时透明显示
                if (mVideoView.isPlaying()) {
                    if (currentLetterLayout != null) {
                        currentLetterLayout.setLayoutSelect(false);
                        currentLetterLayout = null;
                        fontSetting.clearAllAttribute();
                        showAddLetter(true);
                        setEditState(false);
                    }
                    operationLayout.setLayoutTransparent();
                } else {
                    operationLayout.setLayoutSelect(operationLayout.isSelected());
                }
            }

        }
    }

}